import { uuid } from "../utils/Uuid";
import axios from 'axios';

export default class HgcMapBoxUtil {

  /**
   * 构造函数
   * @param map  mapboxgl
   */
  constructor(map, sf) {
    this.map = map;
    this.sf = sf;
  }

  //获取sf
  getSortFactory() {
    return this.sf;
  }

  /**
   * 获取地图
   * @returns {*}
   */
  getMap() {
    return this.map;
  }

  /**
    * 自定义服务(Mapboxgl geojson图层)
    */
  addHgcCustomLayer(layerId, layerUrl, minZoom, maxZoom, isQuery, filter) {
    try {
      if (this.isLayerExist(layerId)) {
        console.warn('添加矢量瓦片>>图层ID为:' + layerId + '已经存在!');
        return;
      }

      this.sf.addHgcCustomLayer(layerId, layerUrl, minZoom, maxZoom, isQuery, filter);
    } catch (e) {
      console.warn(e)
    }
  }

  /**
   * 添加矢量瓦片
   * @param layerId
   * @param layerUrl
   * @param maxZoom
   * @param minZoom
   *
   */
  addVectorTileLayer(layerId, layerUrl, minZoom, maxZoom, isQuery) {
    try {
      if (this.isLayerExist(layerId)) {
        reject('添加矢量瓦片>>图层ID为:' + layerId + '已经存在!');
        return;
      }
      this.sf.addSuperMapLayerByUrl(layerId, layerUrl, minZoom, maxZoom, isQuery);
    } catch (e) {
      console.warn(e)
    }



  }

  /**
   * 添加超图栅格瓦片
   * @param layerId
   * @param layerUrl
   * @param maxZoom
   * @param minZoom
   */
  addGridTileLayer(layerId, layerUrl, minZoom, maxZoom) {

    if (this.isLayerExist(layerId)) {
      console.warn('添加超图栅格瓦片>>图层ID为:"' + layerId + '" 已经存在!');
      return;
    }
    this.sf.addLayer(layerId, {
      id: layerId,
      type: "raster",
      source: {
        type: "raster",
        tiles: [layerUrl],
        tileSize: 256,
        rasterSource: "iserver"
      },
      minzoom: minZoom,
      maxzoom: maxZoom
    })

  }

  /**
   * 添加天地图瓦片服务
   * @param layerId
   * @param layerUrl
   * @param minZoom
   * @param maxZoom
   * @returns {Promise}
   */
  addTdtGridTileLayer(layerId, layerUrl, minZoom, maxZoom,bounds) {
   
    if (this.isLayerExist(layerId)) {
      console.warn('添加天地图瓦片服务>>图层ID为:"' + layerId + '"已经存在!');
      return;
    }

    this.sf.addLayer(layerId, {
      id: layerId,
      type: "raster",
      source: {
        type: "raster",
        tiles: [layerUrl],
        tileSize: 256,
        bounds: bounds ||[-180,-85.051129,180,85.051129] 
      },
      minzoom: minZoom,
      maxzoom: maxZoom
    })
  }

  /**
   * 添加2.5D图层
   * @param layerId
   * @param layerUrl
   * @param minZoom
   * @param maxZoom
   * @returns {Promise}
   */
  addFillExtrusionLayer(layerId, layerUrl, minZoom, maxZoom, isQuery) {
    if (this.isLayerExist(layerId)) {
      console.warn('添加超图2.5D瓦片>>图层ID为:"' + layerId + '" 已经存在!');
      return;
    }
    this.sf.addSuperMapLayerByUrl(layerId, layerUrl, minZoom, maxZoom, isQuery);

    // axios.get(layerUrl).then(res => {
    //   let vectorTileResources = res.data.sources;
    //   layerId = res.data.name;
    //   let layers = res.data.layers;
    //   if (layers && Array.isArray(layers) && layers.length > 0) {
    //     this.map.addSource(layerId, vectorTileResources[layerId]);
    //     this.map.addLayer({
    //       'id': layerId,
    //       'source': layerId,
    //       'source-layer': layers[1]['source-layer'],
    //       // 'filter': ['==', 'extrude', 'true'],
    //       'type': 'fill-extrusion',
    //       'minzoom': 10,
    //       'paint': {
    //         'fill-extrusion-color': '#FCF9F3',
    //         'fill-extrusion-height': [
    //           "interpolate", ["linear"],
    //           ["zoom"],
    //           13, 0,
    //           15.05, ["get", "height"]
    //         ],
    //         'fill-extrusion-base': 0,
    //         'fill-extrusion-opacity': 0.7
    //       }
    //     });
    //     resolve(layers.slice(1));
    //   } else {
    //     resolve({}); //返回sourceId
    //   }
    // }).catch(e => {
    //   reject(e);
    // });


  }

  /**
   * 添加Echart图层
   * @param layerUrl
   * @returns {Promise}
   */
  addEchartsLayer(layerUrl) {
    return new Promise((resolve, reject) => {
      SuperMapQuery.mapServiceLayerSearchBySQL('施工@专题数据', '1=1', layerUrl, features => {
        let data = [];
        for (let i = 0; i < features.length; i++) {
          let fea = features[i];
          data.push({
            'name': fea.properties.ID,
            'value': fea.geometry.coordinates
          });
        }
        let option = {
          GLMap: {
            roam: true
          },
          coordinateSystem: 'GLMap',
          series: [{
            type: 'effectScatter',
            coordinateSystem: 'GLMap',
            data: data,
            symbolSize: 12,
            showEffectOn: 'render',
            rippleEffect: {
              brushType: 'stroke'
            },
            hoverAnimation: true,
            label: {
              normal: {
                formatter: '{b}',
                position: 'right',
                show: false,
                borderColor: '#404a59'
              }
            },
            itemStyle: {
              normal: {
                color: 'orange',
                shadowBlur: 1,
                shadowColor: '#f3f3f3',
                borderWidth: 0
              }
            },
            zlevel: 1
          }]
        };
        let echartLayer = new EchartsLayer(this.map);
        echartLayer.chart.setOption(option, true);
        resolve(echartLayer);
      });
    })

  }

  /**
   * 图层是否存在
   * @param layerId
   * @returns {*}
   */
  isLayerExist(layerId) {
    return this.map.getSource(layerId);
  }


  /**
   * 设置图层透明度
   * @param sourceId
   * @param value
   */
  setLayerOpacity(sourceId, value) {
    let source = this.map.getSource(sourceId);
    if (!source) {
      console.log('图层透明度,数据源ID为：' + sourceId + '不存在');
      return;
    }
    let layers = this.map.getStyle().layers;

    layers.forEach(layer => {
      if (layer.source === sourceId) {
        if (this.isLayerExist(layer.id)) {
          if (layer.type == "fill") {
            this.map.setPaintProperty(layer.id, "fill-opacity", value);
          }
          if (layer.type == "line") {
            this.map.setPaintProperty(layer.id, "line-opacity", value);
          }
          if (layer.type == "raster") {
            this.map.setPaintProperty(layer.id, "raster-opacity", value);
          }
          if (layer.type == "fill-extrusion") {
            this.map.setPaintProperty(layer.id, "fill-extrusion-opacity", value);
          }
        }
      }

    })

  }

  /**
   * 移除矢量瓦片
   * @param sourceId 和layerId一般相同
   */
  removeTileLayer(sourceId) {
    this.sf.removeLayer(sourceId)
  }



























  /**
   * 添加高亮图层  （添加每个图层后，再添加一层高亮图层，显示高亮）
   * @param sourceID     数据源ID
   * @param layer_id     自定义不重复ID
   * @param sourceLayer  sourceLayer
   * @param layerType    图层类型（点线面）
   */
  // addHighLightLayer(sourceID, layer_id, sourceLayer, layerType) {
  //   //console.log(sourceID, layer_id, sourceLayer, layerType)
  //   return new Promise((resolve, reject) => {
  //     let filter = ["in", "smid"];
  //     let fillPaint = {
  //       "fill-color": "#9DC0F8",
  //       "fill-opacity": 0.7
  //     };
  //     let linePaint = {
  //       // "line-color": "#ff0000",
  //       // "line-width": 3,
  //       // "line-opacity": 0.75,
  //       "line-color": "#F5E301",
  //       "line-width": 9
  //     };
  //     let pointPaint = {
  //       "circle-radius": 6,
  //       "circle-color": "#ff0000",
  //       "circle-opacity": 1,
  //       "circle-stroke-width": 2,
  //       "circle-stroke-color": "#ff0000",
  //       "circle-stroke-opacity": 0.5
  //     };
  //     let paintType;
  //     let paint;
  //     if (layerType == 'line') {
  //       paintType = "line";
  //       paint = linePaint;
  //     } else if (layerType == 'fill') {
  //       paintType = "fill";
  //       paint = fillPaint;
  //     } else if (layerType == 'symbol') {
  //       paintType = "circle";
  //       paint = pointPaint;
  //     } else if (layerType == 'circle') {
  //       paintType = "circle";
  //       paint = pointPaint;
  //     }
  //     if (this.isLayerExist(`${layer_id}-highlighted`)) {
  //       reject(`${layer_id}-highlighted` + '图层已经存在!');
  //       return;
  //     }
  //     if (!this.map.getSource(sourceID)) {
  //       reject(sourceID + '-sourceId不存在!');
  //       return;
  //     }
  //     try {
  //       this.map.addLayer({
  //         id: `${layer_id}-highlighted`,
  //         type: paintType,
  //         source: sourceID,
  //         "source-layer": sourceLayer,
  //         paint: paint,
  //         filter: filter
  //       });

  //     } catch (e) {
  //       reject(e);
  //     }
  //     resolve();
  //   });
  // }


  // addHightLightLayers(layerId, source, geoType) {
  //   let filter = ["in", "$type", geoType];
  //   let fillPaint = {
  //     "fill-color": "#9DC0F8",
  //     "fill-opacity": 0.7
  //   };
  //   let linePaint = {
  //     // "line-color": "#ff0000",
  //     // "line-width": 3,
  //     // "line-opacity": 0.75,
  //     "line-color": "#F5E301",
  //     "line-width": 9
  //   };
  //   let pointPaint = {
  //     "circle-radius": 6,
  //     "circle-color": "#ff0000",
  //     "circle-opacity": 1,
  //     "circle-stroke-width": 2,
  //     "circle-stroke-color": "#ff0000",
  //     "circle-stroke-opacity": 0.5
  //   };
  //   let paintType;
  //   let paint;
  //   if (geoType == 'LineString') {
  //     paintType = "line";
  //     paint = linePaint;
  //   } else if (geoType == 'Polygon') {
  //     paintType = "fill";
  //     paint = fillPaint;
  //   } else if (geoType == 'Point') {
  //     paintType = "circle";
  //     paint = pointPaint;
  //   }
  //   this.map.addLayer({
  //     id: `${layerId}-highlighted`,
  //     type: paintType,
  //     source: source,
  //     paint: paint,
  //     filter: filter
  //   });

  // }



  /**
   * 设置高亮图层过滤器
   * @param layerId _id
   * @param fields
   * @returns {Promise}
   */
  // setHighLightFilter(layer_id, fields) {
  //   //console.log(layer_id, fields)
  //   let filter = fields ? ["in", '$id', fields] : ["in", '$id'];
  //   if (!this.isLayerExist(`${layer_id}-highlighted`)) {
  //     console.log(`${layer_id}-highlighted` + ' >> 图层不存在!');
  //     return;
  //   }
  //   this.map.setFilter(`${layer_id}-highlighted`, filter);
  // }


  /**
   * 设置高亮图层过滤器
   * @param layerId _id
   * @param fields
   * @returns {Promise}
   */
  // setHighLightFilter2(layer_id, fields) {

  //   // let filter = fields ? ["in", 'id', fields] : ["in", 'id'];

  //   let filter = fields ? ["==", "$id", fields] : ["==", "$id"];
  //   if (!this.isLayerExist(`${layer_id}-highlighted`)) {
  //     console.log(`${layer_id}-highlighted` + '>>图层不存在!');
  //     return;
  //   }
  //   this.map.setFilter(`${layer_id}-highlighted`, filter);
  // }




  /**
   * 清除高亮图层过滤去
   * @param layerId
   * @param searchField
   */
  // clearHighLightFilter(layer_id) {
  //   return this.setHighLightFilter(layer_id, undefined);
  // }


  /**
   * 加载图片异步
   * 判断图片url地址是否正常
   * 
   * @param id
   * @param url  图片的地址
   */
  addImage(id, url) {
    if (!this.map.hasImage(id)) {
      this.map.loadImage(url, (err, img) => {
        if (err) return;
        this.map.addImage(id, img);
      })
    }
  }

  //加载
  addPng(id, img) {
    if (!this.map.hasImage(id)) {
      this.map.addImage(id, img);
    }
  }

  /**
   * 添加Source
   * @param sourceId
   * @returns {Promise}
   */
  addSource(sourceId, geoJson) {
    return new Promise((resolve, reject) => {
      if (this.map.getSource(sourceId)) {
        reject('添加数据源ID为' + sourceId + '已经存在!');
        return;
      }
      this.map.addSource(sourceId, geoJson);
      resolve(sourceId);
    })
  }

  /**
   * 删除Source
   * @param sourceId
   * @returns {Promise}
   */
  removeSource(sourceId) {
    return new Promise((resolve, reject) => {
      if (!this.map.getSource(sourceId)) {
        reject(sourceId + 'SourceID不存在!');
        return;
      }
      this.map.removeSource(sourceId);
    })
  }

  /**
   * 获取中心点
   * @param url
   * @returns {AxiosPromise<any>}
   */
  getBoundfromServer(url) {
    return axios.get(url);
  }


}









